<?php
/**
 * JWT(Json Web Token)
 *
 */
class JWT
{
    private $issuer;      // Token签发者
    private $timestamp;   // Token签发时间
    private $expire;      // Token失效时间
    private $userId;      // 用户id
    private $type;        // JWT类型
    private $alg;         // 签名算法
    private $signKey;     // 签名密钥
    public function __construct($userId, $expire, $signKey, $issuer='Loyalli', $type='JWT', $alg='SHA256')
    {
        $this->userId = $userId;
        $this->timestamp = time();
        $this->expire = $expire;
        $this->signKey = $signKey;
        $this->issuer = $issuer;
        $this->type = $type;
        $this->alg = $alg;
    }

    /**
     * 生成JWT Token
     */
    public function token()
    {
        $header = base64_encode(json_encode(array('type' => $this->type,'alg'=>$this->alg ))); // base64_decode()
        $playload = base64_encode(json_encode(array('userId' => $this->userId,'timestamp'=>$this->timestamp,'expire'=>$this->expire )));
        return $header.'.'.$playload.'.'.self::signature($header.'.'.$playload, md5($this->signKey), $this->alg);
    }

    /**
     * 生成JWT签名
     * @param  string $input [JWT头部和Playload部分用.号相连]
     * @param  string $key   [签名秘钥md5编码后的值]
     * @param  string $alg   [签名算法]
     * @return [type]        [签名]
     */
    public static function signature(string $input, string $key, string $alg)
    {
        return hash_hmac($alg, $input, $key);
    }
}
